package com.hourse.app.utils;

import com.hourse.platform.exception.AppException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * pdf工具类
 *
 */
public class PdfUtil {
    /**
     * 将pdf转成一张图片
     */
    public static String getPDFBinary(String pdffile) throws IOException, AppException {
        //文件流
        InputStream inputStream = new FileInputStream(pdffile);
        //文件 获取文件名字
        File file = new File(pdffile);
        String name = file.getName();
        //截取不带后缀名的字段
        String fileName = name.substring(0, name.lastIndexOf("."));

        //文件上传路径
        String parent = file.getParent();

        PDDocument doc = PDDocument.load(inputStream);
        //获取pdf文件 页数
        List<PDPage> pages = doc.getDocumentCatalog().getAllPages();

        List<BufferedImage> imageList = new ArrayList<BufferedImage>();
        BufferedImage image = null;
        for (int i = 0; i < pages.size(); i++) {
            PDPage page = (PDPage) pages.get(i); // 获取第i页
            image = page.convertToImage();
            imageList.add(image);
            //合并一张
            // image = MergeImage.mergeImage(false, imageList);
        }

        boolean png = ImageIO.write(image, "png", new File(parent + "/" + fileName + ".png"));
        if (png == false) {
            throw new AppException("转换失败");
        }

        //关闭流
        inputStream.close();
        return parent + "/" + fileName + ".png";


    }


    public static void main(String[] args) throws IOException {
        // PdfUtil.getPDFBinary("C:/Users/Administrator/Desktop/financebill/open-financ-bill-41958377374267444-ok.pdf");
    }

}
